package engine.newUi
{
	import engine.control.MiniLoadingBar;
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.View;
	import engine.data.ViewObject;
	import engine.event.SceneEvent;
	import engine.flag.ResourcesPath;
	import engine.tip.TipsMainLogic;
	
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.display.SimpleButton;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	
	import newx.com.config.StaticIni;
	import newx.com.control.window.NxWindowEvent;
	import newx.com.loader.SwfLoader;
	import newx.utils.MemoryOptimise;

	public class SpecialKungFuLogic
	{
		private static var _self:SpecialKungFuLogic;
		
		private var _ui	: SpecialKungFuUI;
		private var _bindManager 	: BindManage;
		private var _model			: ModelLocator;
		
		private var _pointfalg		: int = -1
		private var _bindFlag		: int = -1;
		private var _falg			: int =	-1;
		
		
		private const IMG:String		= "img";
		private const TXT:String		= "txt_";
		private const USESKILL:String	= "useSkillBtn";
		
		private const BTN:String		= "url_";
		
		private const HELP:String		= "helpbtn"

		private var UrlObj:Object ={};
		private var _currMainMc:MovieClip;
		private var _isShow:Boolean = false;
		private var _allKungfuStree:Vector.<SkillStree>;
		
		
		private var _currUrl:String;
		
		private var _currExp:int=0;
		private const BASE_STATE:int=1,OVER_STATE:int=2,OFF_STATE:int=3;
		
		private var  _hightVec:Object ={};
		public static function getInstance():SpecialKungFuLogic
		{
			if(_self == null)
			{
				_self = new SpecialKungFuLogic();
				
			}
			return _self;
		}
		public function SpecialKungFuLogic()
		{
			
		}
		
		public function Init():void
		{
			_ui					= SpecialKungFuUI.getInstance();
			_model				= ModelLocator.getInstance();
			_bindManager		= BindManage.getInstance();
			_allKungfuStree		= new Vector.<SkillStree>();
			_model.addEventListener( SceneEvent.SceneLoaded, sceneOK );
		}
		private function sceneOK(e:SceneEvent):void
		{
			readIni();
			bind();
		}
		private function readIni():void
		{
			if(_allKungfuStree.length==0)
			{
				var obj:Object =new Object();
				var index:int =_model.scene.Role.getPlayNation();
				while(obj)
				{
					obj = StaticIni.getIniObj("stunt_tree_"+index);
					if(obj ==null) continue;
					index =3;
					index ++;
					var skillArr:Array =( obj["Skill"] as String ).split(",");
					for(var i:String in skillArr)
					{
						_allKungfuStree.push(new SkillStree(int(skillArr[int(i)])));
					}
				}
			}
		}
		private function addEvent():void
		{
			_ui.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,onClose);
		}
		private function removeEvent():void
		{
			_ui.windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE,onClose);
		}
		private function onClose(e:NxWindowEvent):void
		{
			_ui.hide();
		}
		public function BeforeShow():void
		{
			addEvent();
		}
		public function AfterHide():void
		{
			removeEvent();
		}
		private function bind():void
		{
			if(_falg == -1)
			{
				_falg = _bindManager.BindRecord(_model.scene,"AllUpgradeSkillRec",addFunc,removeFunc);
			}
			if( _bindFlag == -1 )
			{
				_bindFlag		=	_bindManager.BindView(_model.scene,View.VIEWPORT_TOOL,OnAddPack,OnRemovePack,null,updatafunc);
				
			}
			if(_pointfalg == -1)
			{
				_pointfalg = _bindManager.BindProp(_model.scene.Role,"SkillExp",this,"skillPonit");
			}
		}
		public function unbind():void
		{
			if(_falg != -1)
			{
				_falg = _bindManager.UnbindRecord("AllUpgradeSkillRec",_falg);
			}
			if( _bindFlag != -1 )
			{
				_bindFlag		=	_bindManager.UnbindView(View.VIEWPORT_TOOL,_bindFlag);
			}
			if(_pointfalg != -1)
			{
				_pointfalg = _bindManager.UnbindProp(_model.scene.Role,"SkillExp",_pointfalg);
			}
		}
		public function set skillPonit(val:int):void
		{
			_currExp = val;
			updateStree();
		}
		private function OnAddPack(PropertiesName:String,PropertiesValue:ViewObject,data:*):void
		{
			var ItemArr:Array = needItemArr();
			if(ItemArr.indexOf(PropertiesValue.GetProperties("ConfigID")) != -1)
			{
				updateStree();
			}
		}
		private function updatafunc(PropertiesName:String,PropertiesValue:ViewObject,data:*):void
		{
			var ItemArr:Array = needItemArr();
			if(ItemArr.indexOf(PropertiesValue.GetProperties("ConfigID")) != -1)
			{
				updateStree();
			}
		}
		private function OnRemovePack(PropertiesName:String,PropertiesValue:ViewObject,data:*):void
		{
			var ItemArr:Array = needItemArr();
			if(ItemArr.indexOf(PropertiesValue.GetProperties("ConfigID")) != -1)
			{
				updateStree();
			}
		}
		private function addFunc(PropertiesName:String,val:*,data:*):void
		{
			var curr:int = val[1];
			var next:int = val[2];
			var configid:int = int(StaticIni.getIniVar(next,"PlayerCategory"))||int(StaticIni.getIniVar(curr,"PlayerCategory"));
			var stree:SkillStree = new SkillStree(configid);
			stree.curr = curr;
			stree.next = next;
			updateKungfu(stree);
			if(_ui.created)
				updateStree();
		}
		private function needItemArr():Array
		{	
			var allSkillArr:Array = StaticIni.getIniVar(_currUrl,"Skill").split(",");
			var stree:SkillStree 
			var itemArr:Array =[];
			var needItem:int=0;
			for(var i:int=0; i<allSkillArr.length; i++)
			{
				stree = getKungfuByID(int(allSkillArr[i]));
				needItem	= int(StaticIni.getIniVar(stree.next,"NeedItem"));
				if(needItem !=0 && itemArr.indexOf(needItem)==-1)
				{
					itemArr.push(needItem);
				}
			}
		   return itemArr;
			
		}
		private function updateStree():void
		{
			var allSkillArr:Array = StaticIni.getIniVar(_currUrl,"Skill").split(",");
			var mc:MovieClip;
			var stree:SkillStree 
			for(var i:int=0; i<allSkillArr.length; i++)
			{
				stree = getKungfuByID(int(allSkillArr[i]));
				mc 	  = getKungfuMc(stree.configid);
				if(mc && stree)
				{
					updateUIState(stree,mc);
					if(stree.next && stree.curr)
					{
						if(mc.currentFrame == OFF_STATE)
							mc.gotoAndStop(BASE_STATE);
					}
					else if(!stree.curr)  //未学
					{
						var needItem:int = int(StaticIni.getIniVar(stree.next,"NeedItem"));
						if(needItem)
						{
							var needItemNum:int =  ComposeItemLogic.getInstance().searchItem(needItem,1);
							if(needItemNum<1)
							{
								mc.gotoAndStop(OFF_STATE);
							}
							else
							{
								mc.gotoAndStop(BASE_STATE);
							}
							
						}
						else
						{
							if(mc.currentFrame == OFF_STATE)
								mc.gotoAndStop(BASE_STATE);
						}
					}
					else
					{
						if(mc.currentFrame == OFF_STATE)
							mc.gotoAndStop(BASE_STATE);
					}
					
				}
			}
		}
		private function updateUIState(skill:SkillStree,mc:MovieClip=null):void
		{
			var _needExp:int		= int(StaticIni.getIniVar(skill.next,"NeedExp"));
			var per:Number 			= 0 ;
			var needItem:int		= 0 ;
			per = _currExp/_needExp>1?1:_currExp/_needExp;
			needItem	= int(StaticIni.getIniVar(skill.next,"NeedItem"));
			if(needItem !=0)
			{
				var haveItemNum:int = ComposeItemLogic.getInstance().searchItem(needItem,1);
				var needItemNum:int = int(StaticIni.getIniVar(skill.next,"NeedItemNum"));
				per =haveItemNum/needItemNum>1?1:haveItemNum/needItemNum;
				
			}
			if(skill.next ==0)
			{
				per =0;
			}
			(mc["bar"] as MovieClip).mouseChildren = (mc["bar"] as MovieClip).mouseEnabled = false;
			(mc["bar"] as MovieClip).height =_hightVec[mc.name]?int(_hightVec[mc.name])*per:per*140;
			(mc["up"] as MovieClip).mouseChildren = (mc["up"] as MovieClip).mouseEnabled = false;
			(mc["up"] as MovieClip).visible = per >=1?true:false;
			(mc["up"] as MovieClip).play();
		}
	
		private function getKungfuMc(id:int):MovieClip
		{
			if(_currMainMc)
			{
				return _currMainMc[BTN+id];
			}
			return null;
		}
		private function removeFunc(PropertiesName:String,val:*,data:*):void
		{
			
		}
		private function updateKungfu(s:SkillStree):void
		{
			for(var i:int=0; i< _allKungfuStree.length; i++)
			{
				if(_allKungfuStree[i].configid == s.configid)
				{
					_allKungfuStree[i] = s;
				}
			}
			if(SpecialKungfuInfoUI.getInstance().created && s.configid == SpecialKungfuInfoLogic.getInstance().currSkill.configid)
			{
				SpecialKungfuInfoLogic.getInstance().currSkill = s;
			}
		}
		public function getKungfuByID(id:int):SkillStree
		{
			for(var i:int=0; i< _allKungfuStree.length; i++)
			{
				if(_allKungfuStree[i].configid == id)
				{
					return _allKungfuStree[i] ;
				}
			}
			
			return new SkillStree(id);
		}
		public function onLoadUrl(swfUrl:String =""):void
		{
			if(swfUrl == "")
			{
				swfUrl 	= "stunt_tree_"+_model.scene.Role.getPlayNation();
				_isShow = true;
			}
			else
			{
				_isShow = false;
			}
			var isHave:Function =new Function();
			isHave = function ():Boolean
			{
				for(var i:String in UrlObj)
				{
					if(i ==swfUrl)
					{
						return true;
					}
				}
				return false;
			}
		
			var b:Boolean = isHave();
			if(b)
			{
				onComplete(UrlObj[swfUrl] as DisplayObject , []);
			}
			else
			{
				MiniLoadingBar.getInstance().show(StaticIni.getSwfLangStr("UIString_1000628"));
				SwfLoader.StartLoad(ResourcesPath.getSpecialKungFuModel(swfUrl),null,onComplete,[onLoading,swfUrl]);
			}
		}
		private function onComplete(val:DisplayObject, pList:Array):void
		{
			if(val)
			{	
				MemoryOptimise.stopMovie(val as DisplayObjectContainer);
				if(_currMainMc && _currMainMc.hasEventListener(MouseEvent.CLICK))
				{
					_currMainMc.removeEventListener(MouseEvent.CLICK,onClick);
					_currMainMc.removeEventListener(MouseEvent.MOUSE_OUT,onOut);
					_currMainMc.removeEventListener(MouseEvent.MOUSE_OVER,onOver);
				}
				_currMainMc= val as MovieClip;
				if(pList.length>1)
				{
					var swfUrl:String = pList[1];
					UrlObj[swfUrl] = _currMainMc;
					_currUrl = swfUrl
					saveMaskHight();
				}
				
				if(_isShow)
					_ui.showUI();
			}
			else
			{
				_currMainMc =null;
				MiniLoadingBar.getInstance().close();
				return ;
			}
			_ui.bgnxclip.source = _currMainMc;
			updateStree();
			if(_currMainMc)
			{
				_currMainMc.mouseChildren = _currMainMc.mouseEnabled=true;
				_currMainMc.addEventListener(MouseEvent.CLICK,onClick);
				_currMainMc.addEventListener(MouseEvent.MOUSE_OUT,onOut);
				_currMainMc.addEventListener(MouseEvent.MOUSE_OVER,onOver);
			}
		}

		private function saveMaskHight():void
		{
			var allSkillArr:Array = StaticIni.getIniVar(_currUrl,"Skill").split(",");
			var mc:MovieClip;
			var stree:SkillStree 
			for(var i:int=0; i<allSkillArr.length; i++)
			{
				stree = getKungfuByID(int(allSkillArr[i]));
				mc 	  = getKungfuMc(stree.configid);
				_hightVec[mc.name] = mc.height;
			}
			
		}
		private function onClick(e:MouseEvent):void
		{
			var mc:MovieClip = e.target as MovieClip;
			if(mc ==null)return;
			
			if(mc.name.indexOf(BTN)>-1)
			{
				var s:SkillStree = getKungfuByID(int(mc.name.replace(BTN,"")));
				if(mc.currentFrame ==OFF_STATE)
				{
					NoticeUI.getInstance().showInfo(StaticIni.getSwfLangStr("SpecialKungfuInfoUIStr_1"));//无扫荡目标
					return ;
				}
				if(SpecialKungfuInfoUI.getInstance().created)
				{
					var obj:DisplayObjectContainer = SpecialKungfuInfoUI.getInstance().parent;
					obj.swapChildren(SpecialKungfuInfoUI.getInstance(),SpecialKungFuUI.getInstance());
				}
				SpecialKungfuInfoLogic.getInstance().currSkill = s;
			}

		}
		private function onOver(e:MouseEvent):void
		{
			if(e.target is SimpleButton)
			{
				TipsMainLogic.instance.showWideString(StaticIni.getSwfLangStr("SpecialKungfuInfoUIStr_8"));
				return ;
			}
			var mc:MovieClip = e.target as MovieClip;
			if(mc ==null)return;
			if(mc.name.indexOf(BTN)>-1 && mc.currentFrame == BASE_STATE)
			{
				mc.gotoAndStop(OVER_STATE);
				if(!mc.buttonMode)
					mc.buttonMode=true;
			}
		
		}
		private function onOut(e:MouseEvent):void
		{
			if(e.target is SimpleButton)
			{
				TipsMainLogic.instance.hide();
				return;
			}
			var mc:MovieClip = e.target as MovieClip;
			if(mc.name.indexOf(BTN)>-1 && mc.currentFrame == OVER_STATE)
			{
				mc.gotoAndStop(BASE_STATE);
			}
		}
		private function onLoading(e:Event):void
		{
			var pe:ProgressEvent=e as ProgressEvent;
			if(pe)
				MiniLoadingBar.getInstance().progress=pe.bytesLoaded/pe.bytesTotal;
		}
	}
		
}
